package com.sinux.generality.basesupport.utils.tool;


import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

public class HttpRequest {
    private static CloseableHttpClient client = HttpClients.createDefault();

    public static String post(String url, JSONObject param) throws IOException{
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(param.toString()));
        HttpResponse response = client.execute(post);
        return EntityUtils.toString(response.getEntity());
    }

    public static String get(String url, JSONObject param) throws IOException, URISyntaxException {
        if(!param.isEmpty()){
            URIBuilder uriBuilder = new URIBuilder(url);
            List<NameValuePair> list = new LinkedList<>();
            for(String key: param.keySet()){
                BasicNameValuePair param1 = new BasicNameValuePair(key, param.getString(key));
                list.add(param1);
            }
            uriBuilder.setParameters(list);
            HttpGet get = new HttpGet(uriBuilder.build());
            HttpResponse response = client.execute(get);
            return EntityUtils.toString(response.getEntity());
        }
        else{
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);
            return EntityUtils.toString(response.getEntity());
        }
    }

    public static String get(String url) throws IOException, URISyntaxException {
        return get(url, new JSONObject());
    }

}
